package exam.wzb.jsp.service.impl;


import exam.wzb.jsp.dao.AccountDao;
import exam.wzb.jsp.dao.impl.AccountDaoImpl;
import exam.wzb.jsp.model.Account;
import exam.wzb.jsp.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.List;


public class AccountServiceImpl implements AccountService {

    private final AccountDao accountDao;

    public AccountServiceImpl(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    @Transactional
    public void addAccount(Account account) {
        accountDao.addAccount(account);
    }

    @Override
    public void transfer(int fromAccountId, int toAccountId, double amount) {

    }

    @Override
    public List<Account> getAllAccounts() {
        return null;
    }


    @Transactional
    public void transferMoney(int fromAccountId, int toAccountId1, int toAccountId2, double amount) throws Exception {
        Account fromAccount = accountDao.findAccountById(fromAccountId);
        Account toAccount1 = accountDao.findAccountById(toAccountId1);
        Account toAccount2 = accountDao.findAccountById(toAccountId2);

        if (fromAccount == null || toAccount1 == null || toAccount2 == null) {
            throw new Exception("One or more accounts do not exist.");
        }

        if (fromAccount.getBalance() < amount) {
            throw new Exception("Insufficient funds.");
        }

        double halfAmount = amount / 2;

        fromAccount.setBalance(fromAccount.getBalance() - amount);
        toAccount1.setBalance(toAccount1.getBalance() + halfAmount);
        toAccount2.setBalance(toAccount2.getBalance() + halfAmount);

        accountDao.updateAccountBalance(fromAccount);
        accountDAO.updateAccountBalance(toAccount1);
        accountDAO.updateAccountBalance(toAccount2);
    }
    @Override
    @Transactional
    public void transfer(int fromAccountId, int toAccountId1, int toAccountId2, double amount) throws Exception {
        accountDao.transfer(fromAccountId, toAccountId1, toAccountId2, amount);


    }


}
